﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using System.Collections;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace EntlibCacheStorage
{
    [ConfigurationElementType(typeof(CustomCacheStorageData))]
    public class CustomDataBackingStore : BaseBackingStore
    {
        private readonly ICacheDataStore _dao;
        private readonly string _partitionName;

        public CustomDataBackingStore(ICacheDataStore dao, string partitionName)
        {
            if (dao == null)
                throw new ArgumentNullException("dao");

            _dao = dao;
            _partitionName = partitionName;
        }

        #region BaseBackingStore
        protected override void AddNewItem(int storageKey, CacheItem newItem)
        {
            Remove(storageKey);
            //string key = newItem.Key;
            //byte[] valueBytes = SerializationUtility.ToBytes(newItem.Value);

            //byte[] expirationBytes = SerializationUtility.ToBytes(newItem.GetExpirations());
            //byte[] refreshActionBytes = SerializationUtility.ToBytes(newItem.RefreshAction);
            //CacheItemPriority scavengingPriority = newItem.ScavengingPriority;
            //long lastAccessedTime = newItem.LastAccessedTime.Ticks;
            _dao.Add(_partitionName, newItem);
        }

        public override int Count
        {
            get { return _dao.Count(_partitionName); }
        }

        public override void Flush()
        {
            _dao.Truncate(_partitionName);
        }

        protected override Hashtable LoadDataFromStore()
        {
            return _dao.Load(_partitionName);
        }

        protected override void Remove(int storageKey)
        {
            _dao.Remove(_partitionName, storageKey);
        }

        protected override void RemoveOldItem(int storageKey)
        {
            Remove(storageKey);
        }

        /// <summary>
        /// 更新最后访问时间
        /// 因为失效时间是从创建时开始，所以此方法不实现 
        /// </summary>
        /// <param name="storageKey"></param>
        /// <param name="timestamp"></param>
        protected override void UpdateLastAccessedTime(int storageKey, DateTime timestamp) { }

        #endregion
    }
}
